import { v4 as uuidv4 } from 'uuid';
import { BaseObserver } from './base.ts';
interface BehaviorData {
  type: string;
  form: string;
  to: string;
  url: string;
  time: string | number;
}

export class BehaviorObserver extends BaseObserver{
    // maxBreadcrumbs控制上报用户行为的最大条数
    private maxBehaviors: number;
    // stack 存储用户行为
    private stack: BehaviorData[] = [];
    constructor({ maxBehaviors = 20}) {
      super();
      this.maxBehaviors = maxBehaviors;
      this.stack = [];
    }
    // 添加用户行为栈
    push(data: BehaviorData) {
      if (this.stack.length >= this.maxBehaviors) {
        // 超出则删除第一条
        this.stack.shift();
      }
      this.stack.push(data);
      // 按照时间排序
      this.stack.sort((a, b) => Number(a?.time) - Number(b?.time));
    }
    public handlePageChange() {
       // hash histroy
      let oldUrl = '';
      window.addEventListener(
          'hashchange',
          (event) => {
              console.error('hashchange', event);
              const newUrl = event.newURL;
              const reportData = {
                  from: oldUrl,
                  to: newUrl,
                  type: 'behavior',
                  subType: 'hashchange',
                  startTime: performance.now(),
                  uuid: uuidv4(),
              };
              this.lazyReportBatch(reportData);
              oldUrl = newUrl;
          },
          true
      );

      let from = '';
      window.addEventListener(
          'popstate',
          (event) => {
              console.error('popstate', event);
              const to = window.location.href;
              const reportData = {
                  from: from,
                  to: to,
                  type: 'behavior',
                  subType: 'popstate',
                  startTime: performance.now(),
                  uuid: uuidv4(),
              };
              this.lazyReportBatch(reportData);
              from = to;
          },
          true
      );
    }
  }

